import { Toast } from "vant";
import goodsCard from "../consumptionComm/goodsCard/goodsCard";
import cTitle from "components/title";
export default {
  components: {
    goodsCard,
    cTitle
  },
  data() {
    return {
      disabled_stepper:false,
      query: {
        //修改订单数据
        goodsId: 0,
        optionsId: "",
        orders: [],
        total: 1,
        memberCouponIds: [],
        note: ""
      },
      orderIds: 0,
      levelName: "",
      privacyDesc: "",
      goodsOrder: [],
      TemplateArray: [], //模板ID发送通知
      clickMiniTemplate: false, //判断是否已经点击订阅订单
      goodsDeductions: [], //爱心值积分抵扣系列
      //优惠券
      cup_notice: true,
      coupon_size: 0,
      useCouponSize: 0,
      checkDeductionList: [],
      deduction_lang: "折扣",
      popupCouponSpecs: false,
      agreementChecked: false,
      orderShow: false,
      totalPrice: 0,
      offlinePrice: "",
      name: "",
      mobile: "",
      pluginSetting: {},
      tagList: [],
      userParams: ["name", "mobile", "query.note"],
      good_clicktag: 0,
      coupons: [],
      checkCouponList: [],
      use_coupon_size: 0,
      stepper_show: 0,
      is_coupon_SELE: false,
      coupons_temp: {}, //折叠优惠券input框model
      timeoutId: null, //防抖，防止折叠优惠券频繁触发
      checkedList: {
        a: false
      }
    };
  },
  activated() {
    this.disabled_stepper = false;
    if(this.$route.query.exchange_code_id){
      this.disabled_stepper = true;
      this.query.total = this.$route.query.total;
    }
    this.query.goodsId = Number(this.$route.query.goodsId);

    this.preOrderData();
    this.orderPay();

  },
  methods: {
    preOrderData() {
      //预下单格外数据
      let json = {
        goods_id: this.query.goodsId,
        basic_info: 1
      };
      $http.post("plugin.coupon-store.frontend.order.preOrderData", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.levelName = res.level_name;
            this.privacyDesc = res.privacy_desc;
            this.offlinePrice = res.offline_price;
            this.pluginSetting = response.basic_info?.plugin_setting?.coupon_store;
            this.tagList = res.tag_list;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    // 组装优惠券json信息
    assembleCoupons() {
      let coupons = [];
      for (let i = 0; i < this.checkCouponList.length; i++) {
        if (this.is_coupon_SELE) {
          //开启折叠优惠券
          let coupon_arr = this.checkCouponList[i].has_conpon_id;
          coupons = coupons.concat(coupon_arr.slice(0, this.coupons_temp[this.checkCouponList[i].coupon_id].num));
          this.use_coupon_size = coupons.length;
        } else {
          coupons.push(this.checkCouponList[i].id);
        }
      }

      return coupons;
    },
    orderPay() {
      //预下单
      let json = {
        goods_id: this.query.goodsId,
        option_id: this.query.optionsId,
        total: this.query.total,
        dispatch_type_id: 0,
        member_coupon_ids: this.assembleCoupons(),
        orders: JSON.stringify(this._assembleDeduction())
      };
      let url = "order.goods-buy";
      if(this.$route.query.exchange_code_id){//兑换码日志id
        url ="plugin.exchange-code.api.goods-buy";
        json.exchange_code_id =this.$route.query.exchange_code_id
      }
      $http.post(url, json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let goodsDeductions = res.orders[0]?.order_deductions;
            if (Object.prototype.toString.call(goodsDeductions) === "[object Object]") {
              //判断是对象转化数组格式
              goodsDeductions = Object.values(res.orders[0]?.order_deductions);
            }
            let orders = [];
            orders.push({
              pre_id: res.orders[0].pre_id
            });
            // that.defaultSelectCoupon(res.data.discount?.member_coupons);
            this._initCoupon(res.discount); //设置优惠券信息
            this.goodsOrder = res.orders;
            this.totalPrice = res.total_price;
            this.goodsDeductions = goodsDeductions;
            this.checkCouponList = res.discount?.member_coupons;
            this.query.note = res.orders[0]?.note;
            this.query.orders = orders;
            this.query.total = res.orders[0]?.goods_total;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    chooseCoupon(index, valid) {
      if (valid) {
        this.coupons[index].checked = true;
      }
    },
    //初始化优惠券
    _initCoupon(data) {
      if (data.deduction_lang) {
        this.deduction_lang = data.deduction_lang;
      }
      this.isShowCoupon = data.whether_show_coupon == "1" ? true : false;
      let coupon = data.member_coupons;
      this.is_coupon_SELE = data.coupon_show == "1" ? true : false;
      this.coupon_size = coupon.length;
      if (coupon != undefined && coupon != "" && coupon != null) {
        if (this.is_coupon_SELE) {
          //按过期时间排序
          let arr2 = coupon.sort((a, b) => {
            return a.expired_at - b.expired_at;
          });
          this.initSelectCoupon(arr2);
        } else {
          this.coupons = coupon;
          // console.log(typeof this.coupons[0].checked);
        }
      }
    },
    //折叠优惠券
    initSelectCoupon(coupon) {
      let coupon_data = coupon;
      let result = [];
      let temp = {};
      for (let i = 0; i < coupon_data.length; i++) {
        let num = 0; //同类型已选中并符合使用条件的优惠券数量
        let valid = 0; //最高限制使用数量
        let has_conpon_id = [coupon_data[i].id];
        if (coupon_data[i].checked) {
          num++;
        }
        if (coupon_data[i].valid) {
          valid++;
        }
        for (let j = i + 1; j < coupon_data.length; j++) {
          if (coupon_data[i].coupon_id == coupon_data[j].coupon_id) {
            if (coupon_data[j].checked) {
              num++;
            }
            if (coupon_data[j].valid) {
              valid++;
            }
            has_conpon_id.push(coupon_data[j].id);
            coupon_data.splice(j, 1);
            j--;
          }
        }
        let _data = coupon_data[i];
        _data.has_conpon_id = has_conpon_id;
        _data.valid_num = valid;
        result.push(_data);
        temp[coupon_data[i].coupon_id] = {};
        temp[coupon_data[i].coupon_id].num = num;
      }
      this.coupons_temp = temp;
      this.coupons = result;
    },
    //优惠券
    showCoupon() {
      if (this.coupon_size == 0) {
        Toast("暂无优惠券使用");
        return;
      }
      this.popupCouponSpecs = true;
    },
    _assembleDeduction(data) {
      //修改提交的orders数据
      let deductions = [];
      let DeductionsData = [];
      let DeductionsId = [];
      let goodsDeductions = this.goodsDeductions;
      let newObj = {};
      DeductionsData = goodsDeductions.filter(item => {
        //筛选选中的爱心值，积分等等
        return item.checked === true;
      });
      DeductionsData.forEach(item => {
        //获取code值
        DeductionsId.push(item.code);
      });
      this.query.orders.push({
        deduction_ids: DeductionsId,
        note: this.query.note
      });
      this.query.orders.forEach(item => {
        if (item) {
          newObj = { ...newObj, ...item }; // 要把自己放进去
        }
      });
      if (Array.prototype.isPrototypeOf(this.query.orders) && this.query.orders.length !== 0) {
        //不是空数组的时候才添加对象
        deductions.push(newObj);
      }
      return deductions;
    },
    //选择优惠券
    selectCoupon(value, valObj, num) {
      // let ids = [];
      // for (let i in this.coupons) {
      //   if (this.coupons[i].checked) {
      //     ids.push(this.coupons[i].id);
      //   }
      // }
      // this.memberCouponIds = ids;
      // this.useCouponSize = ids.length;
      // 处理选择
      this.screenCoupon(value, valObj, num);
      // 设置已经使用多少优惠券
      this.use_coupon_size = this.checkCouponList.length;

      // 重新计算
      // this.handleBuy("2");
      this.orderPay();
    },
    // 筛选数据优惠券状态
    screenCoupon(value, valObj, num) {
      let tarValue = valObj;
      if (value) {
        // 选中添加
        // this.cup_notice = false;
        if (this.checkCouponList.length > 0) {
          for (let i = 0; i < this.checkCouponList.length; i++) {
            if (this.checkCouponList[i].id == tarValue.id) {
              this.checkCouponList.splice(i, 1);
            }
          }
          this.checkCouponList.push(tarValue);
        } else {
          this.checkCouponList.push(tarValue);
        }

        if (this.is_coupon_SELE && value) {
          //开启折叠优惠券并且为点击复选框为选中状态
          this.coupons_temp[tarValue.coupon_id].num = num || 1;
        }
      } else {
        // 取消选中
        this.cup_notice = true;
        if (this.checkCouponList.length > 0) {
          for (let i = 0; i < this.checkCouponList.length; i++) {
            if (this.checkCouponList[i].id == tarValue.id) {
              this.checkCouponList.splice(i, 1);
            }
          }
        }
        if (this.is_coupon_SELE && !value) {
          //开启折叠优惠券并且为点击复选框为选中状态
          this.coupons_temp[tarValue.coupon_id].num = 0;
        }
      }
    },
    changeConpon(num, data) {
      let valObj = data.name;
      if (num > valObj.valid_num) {
        Toast("使用张数已达上限");
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          // 注意此时修改 value 后会再次触发 change 事件
          this.coupons_temp[valObj.coupon_id].num = valObj.valid_num;
        }, 200);
        return;
      } else if (num == "" || num == undefined || num == 0) {
        Toast("暂不使用请取消勾选");
        return;
      } else {
        clearTimeout(this.timer);
        this.coupons_temp[valObj.coupon_id].num = num;
      }

      // clearTimeout方法，以便控制连续触发带来的无用调用
      let value = {
        target: { checked: true }
      };
      if (this.timeoutId) {
        clearTimeout(this.timeoutId); // 先清除之前的延时，并在下面重新开始计算时间
      }
      this.timeoutId = setTimeout(() => {
        // 100毫秒以后执行方法
        this.selectCoupon(value, valObj, num);
      }, 200); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
    },
    //筛选数据优惠券状态
    _screenCoupon(couponBol, valObj, num) {
      let tarValue = valObj;
      let checkCouponList = this.checkCouponList;
      if (this.checkCouponList.length > 0) {
        for (let i = 0; i < this.checkCouponList.length; i++) {
          if (this.checkCouponList[i].id == tarValue.id) {
            checkCouponList.splice(i, 1);
          }
        }
      }
      if (this.is_coupon_SELE && couponBol) {
        //开启折叠优惠券并且为点击复选框为选中状态
        this.coupons_temp[tarValue.coupon_id].num = couponBol ? 1 : 0;

        // this.setData({
        //   coupons_temp: this.coupons_temp
        // });
      }
      if (couponBol) {
        //选中添加
        checkCouponList.push(tarValue);
      } else {
        //取消选中
        this.cup_notice = true;
      }

      this.checkCouponList = checkCouponList;
    },
    modelInput(value, index) {
      this.userParams[index] = value;
    },
    onAgreementChange(event) {
      this.agreementChecked = event;
    },
    onLikeChange(index) {
      this._assembleDeduction();
      this.orderPay();
    },
    onClose() {
      // this.setData({
      //   orderShow: false
      // });
      this.orderShow = false;
    },
    couponclose() {
      this.popupCouponSpecs = false;
    },
    onAgreement() {
      this.orderShow = true;
    },
    onOrderSubmit() {
      this.onOrderPay();
    },
    onOrderPay() {
      if (!this.name) {
        Toast("请输入姓名");
        return;
      }
      if (!this.mobile) {
        Toast("请输入手机号");
        return;
      }
      if (!this.agreementChecked) {
        Toast("请同意个人信息保护声明");
        return;
      }
      let goods = [];
      goods.push({
        goods_id: this.query.goodsId,
        option_id: this.query.optionsId,
        total: this.query.total
      });
      let json = {
        dispatch_type_id: 0,
        name: this.name,
        mobile: this.mobile,
        member_coupon_ids: this.assembleCoupons(),
        goods: JSON.stringify(goods),
        orders: JSON.stringify(this._assembleDeduction())
      };
      if(this.$route.query.exchange_code_id){//兑换码日志id
        json.exchange_code_id = this.$route.query.exchange_code_id
      }
      let url = 'order.create';//下单url
      if(this.$route.query.exchange_code_id){
        url='plugin.coupon-store.frontend.create.index'
      }
      $http.post(url, json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.orderIds = res.order_ids;
            Toast.loading({
              message: "加载中...",
              forbidClick: true
            });
            let orderJson = {
              status: "2",
              order_ids: this.orderIds
            };
            //判断是否同意消息通知
            this.$router.replace(this.fun.getUrl("orderpay", orderJson));
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    onTotalChange(value) {
      //修改数量
      Toast.loading({ forbidClick: true });
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        Toast.clear();
        // 注意此时修改 value 后会再次触发 change 事件
        this.query.total = value;
        this.orderPay();
      }, 500);
    }
  }
};
